<?php


namespace app\common\service\sms;


use app\common\exception\MiException;
use app\common\service\CommonSiteConfigService;
use app\common\service\CommonStoreManagerService;
use app\common\service\traits\InstanceTrait;
use app\extend\MiCurl;
use JetBrains\PhpStorm\NoReturn;
use think\facade\Cache;

/**
 * 企信短信平台
 */
class SmsService {


    protected static ?self $_instance = null;
    private array $config;

    public static function instance(int $siteId):static
    {
        if (!self::$_instance){
            self::$_instance = new self($siteId);
        }
        return self::$_instance;
    }

    private function __construct(int $siteId)
    {
        $this->config = CommonSiteConfigService::instance()->getConfigValue($siteId, CommonSiteConfigService::SMS);
    }


    /**
     * 发送短信
     * @throws MiException
     */
    public function send($mobile, $content)
    {
        $showType = $this->config['show_type'];
        switch ($showType){
            case 'ali':
                $this->aliSend($mobile, $content);
                break;
            case 'qixin':
                $this->qixinSend($mobile, $content);
                break;
        }

    }

    public function saveCode(){

    }

    public function validateCode($code, $type, $mobile): bool
    {
        // 验证短信验证码
        $verifyKey = 'verify'.$type.$mobile;
        $smsCode = Cache::get($verifyKey, '');
        if ($smsCode != $code){
            return false;
        }
        // 删除验证码
        Cache::delete($verifyKey);
        return true;

    }

    /**
     * @throws MiException
     * @throws \Exception
     */
    private function qixinSend(string $mobile, string $content): void
    {
        header("Content-Type:text/html;charset=utf-8");

//        //url地址
//        $sms_url = '39.105.41.54:8888/v2sms.aspx';
//        //企业id
//        $userid ='15';
//        //时间戳
//        $timestamp = time();
//        //签名md5小写加密
//        $sign= md5('zhwswlhyws954826'.$timestamp);
//        $str = '【鹰智物流网】您好：有客户通过鹰智物流网查看您的联系方式或通过一键拨号功能向您致电，感谢您的支持！如需帮助请拨打0536-8988288';
//        "【优特惠折扣仓】有顾客下单，请及时处理"

        $config = $this->config['qixin'];
        $url = $config['url'];
        $userid = $config['uid'];
        $timestamp = time();
        $sign = md5($config['account'].$config['password'].$timestamp);
        $params = 'action=send&rt=json&userid='.$userid.'&timestamp='.$timestamp.'&sign='.$sign.'&mobile='.$mobile.'&content='.$content.'&sendTime=&extno=';

        // 发送短信
//        $redata= json_decode(curlRequest($url,$params,'POST'), true);
        $header = array("Content-type: application/x-www-form-urlencoded; charset=utf-8");
        $redata = MiCurl::instance()->post($url, $params, $header)->toArray();
        if ($redata['ReturnStatus'] != 'Success'){
            throw new MiException($redata['Message']);
        }
    }


    private function aliSend($mobile, $content){

        $system = System::getSystem();

        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $system['sms_ali_id'],
            // 您的AccessKey Secret
            "accessKeySecret" => $system['sms_ali_secret']
        ]);
        // 访问的域名
        $config->endpoint = $system['sms_ali_endpoint'];
        $client =  new Dysmsapi($config);

        $args = [
            'phoneNumbers' => $mobile,
            'signName' => $signName,
            'templateCode' => $tCode,
        ];

        if (count($param) > 0){
            $args['templateParam'] = json_encode($param);
        }


        $sendSmsRequest = new SendSmsRequest($args);
        // 复制代码运行请自行打印 API 的返回值
        $res = $client->sendSms($sendSmsRequest);

        $resb = ($res->toMap())['body'];

        $data = ['error'=>0, 'msg'=>'发送成功'];
        if ($resb['Code'] != 'OK'){  // 发送失败
            $data['error'] = $resb['Code'];
            $data['msg'] = $resb['Message'];
        }

        return $data;

    }
}


